package vn.com.atm;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vn.com.atm.database.UserFunctions;
import vn.com.atm.library.LoadBitmap;
import vn.com.atm.obj.AtmObj;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;

public class SearchActivity extends Activity {

	private Spinner spnBank, spnDistrict;
	private Button btnViewMap, btnSearch, btnCancel;
	private EditText edAtmCode, edAddress;
	private static final String TAG_BANK = "bank";
	private static final String TAG_BANK_NAME = "bankName";
	private static final String TAG_ATM = "atm";

	private static final String TAG_BANK_CODE = "bankCode",
			TAG_ATM_CODE = "atmCode", TAG_ADDRESS = "address";
	String bankCode, atmCode, address = "", district, branch;
	JSONArray atm, arrquan;
	// Hien thi list view
	public static ArrayList<AtmObj> arrayregister;
	public static AdapterRegister adapter;
	JSONArray arrBank;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		UserFunctions userFunction = new UserFunctions();
		JSONObject json = userFunction.listBank();

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_search);

		spnBank = (Spinner) findViewById(R.id.spnBank);

		// Create array
		ArrayAdapter<CharSequence> adapBank = new ArrayAdapter<CharSequence>(
				SearchActivity.this, android.R.layout.simple_spinner_item);
		// ArrayAdapter<CharSequence> adapBank = new
		// ArrayAdapter<CharSequence>(SearchActivity.this,
		// R.layout.spinner_layout);
		adapBank.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// set adapter

		spnBank.setAdapter(adapBank);
		// Set selected Listener

		try {
			if (json.getString(TAG_BANK) != null) {
				arrBank = json.getJSONArray(TAG_BANK);
				adapBank.add("Tất cả");
				for (int i = 0; i < arrBank.length(); i++) {
					JSONObject ojbBank = arrBank.getJSONObject(i);
					String bank = ojbBank.getString(TAG_BANK_NAME);
					adapBank.add(bank);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		spnBank.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> adap, View v,
					int position, long arg3) {

				try {
					//bankCode = URLEncoder.encode(
					//		adap.getItemAtPosition(position).toString(),
					//		"UTF-8");
					if(position == 0)
						bankCode = "";
					else
						bankCode = arrBank.getJSONObject(position-1).getString(TAG_BANK_CODE);
					
				} catch (Exception e) {
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
					bankCode = "";
			}
		});

		spnDistrict = (Spinner) findViewById(R.id.spnDistrict);
		// Create array
		ArrayAdapter<CharSequence> adapDist = new ArrayAdapter<CharSequence>(
				SearchActivity.this, android.R.layout.simple_spinner_item);
		// ArrayAdapter<CharSequence> adapBank = new
		// ArrayAdapter<CharSequence>(SearchActivity.this,
		// R.layout.spinner_layout);
		adapDist.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		JSONObject js = userFunction.listDistrict();
		// set adapter
		try {
			if (js.getString("quanhuyen") != null) {
				adapDist.add("Tất cả");
				arrquan = js.getJSONArray("quanhuyen");
				for (int i = 0; i < arrquan.length(); i++) {
					JSONObject ojquan = arrquan.getJSONObject(i);
					String quan = ojquan.getString("tenQuan");
					adapDist.add(quan);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		spnDistrict.setAdapter(adapDist);
		spnDistrict.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> adap, View v,
					int position, long arg3) {

				try {
					//district = URLEncoder.encode(
					//		adap.getItemAtPosition(position).toString(),
					//		"UTF-8");
					if(position ==  0)
						district = "";
					else
						district = arrquan.getJSONObject(position-1).getString("maQuan");
				} catch (Exception e) {
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
					district = "";
			}
		});

		// radio button

		RadioGroup rd = (RadioGroup) findViewById(R.id.rdBranch);
		rd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.rdButtonY:
					branch = "1";
					break;
				case R.id.rdButtonN:
					branch = "0";
					break;
				default:
					break;
				}

			}
		});

		// Set selected Listener
		// Button search
		arrayregister = new ArrayList<AtmObj>();
		adapter = new AdapterRegister(this, R.layout.list_row, arrayregister);

		btnSearch = (Button) findViewById(R.id.btnSearch);
		edAddress = (EditText) findViewById(R.id.edAddress);
		btnSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				address = edAddress.getText().toString();

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
						AllATMActivity.class);
				// sending pid to next activity
				UserFunctions userFunction = new UserFunctions();
		
				JSONObject json = userFunction.searchATM(bankCode, district, address, branch);

				atm = new JSONArray();
				// Check your log cat for JSON reponse
				Log.d("All ATM: ", json.toString());

				try {
					// Checking for SUCCESS TAG
					if(json.getString("size").equals("0"))
					{
						AtmObj item = new AtmObj(null, "Không tìm thấy dữ liệu", null, null, null, null);
						arrayregister.add(0, item);
					}
					else
					{
						if (json.getJSONArray(TAG_ATM) != null) {
							// products found
							// Getting Array of Products
							LoadBitmap bm = new LoadBitmap();
							atm = json.getJSONArray(TAG_ATM);
							// looping through All Products
							for (int i = 0; i < atm.length(); i++) {
								JSONObject c = atm.getJSONObject(i);

								// Storing each json item in variable
								String atmCode = "Mã máy: " + c.getString(TAG_ATM_CODE);
								String bankCode = "Ngân hàng:  " + c.getString(TAG_BANK_CODE);
								String address = "Địa chỉ: " + c.getString(TAG_ADDRESS);
								String latatude = c.getString("latitude");
								String longtatude = c.getString("longitude");
								String imgURL = c.getString("imageFile");
								Bitmap bm1 = bm.loadBitmap(imgURL);

								AtmObj item = new AtmObj(atmCode, bankCode, address, latatude, longtatude, bm1);
								
								arrayregister.add(0, item);

							}
						} else {
							// no products found
							// Launch Add New product Activity
							Intent i = new Intent(getApplicationContext(),
									MainActivity.class);
							// Closing all previous activities
							i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(i);
						}
					}
					
				} catch (JSONException e) {
					e.printStackTrace();
				}

				startActivity(in);

			}
		});

		// Button Cancel
		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(getBaseContext(), MainActivity.class);
				startActivity(i);

				finish();
			}
		});

	}

	public class AdapterRegister extends ArrayAdapter<AtmObj> {
		Context mcontext;
		int rource;
		ArrayList<AtmObj> array;

		public AdapterRegister(Context context, int textViewResourceId,
				ArrayList<AtmObj> arrays) {
			super(context, textViewResourceId, arrays);

			this.mcontext = context;
			this.array = arrays;
			this.rource = textViewResourceId;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			AtmObj item;

			if (view == null) {
				view = getLayoutInflater().inflate(R.layout.list_row, null);
			}
			if ((item = this.array.get(position)) == null) {
				return view;
			}

			ImageView icon = (ImageView) view.findViewById(R.id.list_image);
			//TextView atmName = (TextView) view.findViewById(R.id.atmName);
			TextView bankName = (TextView) view.findViewById(R.id.bankName);
			TextView address = (TextView) view.findViewById(R.id.address);
			//TextView lat = (TextView) view.findViewById(R.id.lat);
			//TextView longt = (TextView) view.findViewById(R.id.longtatude);

			icon.setImageBitmap(item.bm);
			//atmName.setText(item.atmCode);
			bankName.setText(item.bankCode);
			address.setText(item.address);
			//lat.setText(item.lat);
			//longt.setText(item.longt);

			return view;
		}

	}

}
